import './assets/main.css'
import '../public-path'

import { createApp } from 'vue'
import { createPinia } from 'pinia'

import App from './App.vue'
import router from './router'
import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

let app: any
function render(props = {}) {
  // 每一次render都需要创建一个新的
  app = createApp(App)
  app.use(createPinia())
  app.use(router)
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
  }
  app.use(ElementPlus)
  const { container } = props as any
  // 挂载到主应用传递的容器中
  app.mount(container ? container.querySelector(`#sub2-app`) : '#sub2-app')
}

const bootstrap: (...args: any[]) => any = () => {
  console.log('mdm app bootstraped')
}

const mount: (...args: any[]) => any = (props) => {
  const { container } = props
  render(props)
  
  // 若用 qiankun 全局状态
  props.onGlobalStateChange?.((state:any) => {
    console.log(state,'state')
    if (state?.app !== 'sub2-app') return      // 只处理自己的
    const t = state.route?.startsWith('/') ? state.route : `/${state.route||''}`
    const cur = router.currentRoute.value.path
    console.log(t,cur,'t,cur')
    if (t && t !== cur) router.replace(t)      // 只在不同才跳
  }, false)

  // 获取容器DOM
  app.config.globalProperties.$topDom = container.querySelector(`#sub2-app`)
  console.log('sub2-app mount')
}

const unmount: (...args: any[]) => any = () => {
  app.unmount()
}

const initQianKun = () => {
  // @ts-ignore
  renderWithQiankun({
    mount,
    bootstrap,
    unmount,
  })
  // render()
}

qiankunWindow.__POWERED_BY_QIANKUN__ ? initQianKun() : render()

